<template>
  <div>
    <!--  主页导航栏-->
    <div class="container">

      <div class="left" v-show="showSpan1">
        <span style="font-size: 20px">去{{endaddress}}</span><br>
        <span style="font-size: 12px">全程
        <span style="flood-color: violet">{{driverLong}}</span>
        公里 全程约<span style="flood-color: violet">{{driverTime}}</span>
        分钟</span>
      </div>

      <div v-if="showSpan1===false">
        <p style="text-align: center">已到达约定地点,请等待乘客上车</p>
      </div>
      <div class="right">
        <van-button plain type="primary" style="font-size: 12px;width: 80px">行程信息</van-button>
      </div>
    </div>
    <van-divider style="background-color: black;margin-top: -2px"></van-divider>
    <div v-show="showSpan1">
      <span style="line-height: 20px;text-align: left;display: inline-block">请在 <span style="color: red">{{driverTime+5}}分钟</span> 内到达出发点</span>
    </div>

    <van-sticky :offset-top="880" z-index="100">
      <div class="custom-layout">
        <div class="custom-item" v-show="showSpan1" style="background-color: #ff9959" @click="showSpanMain()">
          <span style="line-height: 30px; color: white;">确认到达</span>
        </div>
        <div class="custom-item" :style="{ backgroundColor: '#4ea9cb', width: showSpan1 ? '30%' : '80%'}">
          <!--        点击接到乘客以后显示的遮罩层-->
          <span style="line-height: 30px; color: white;" @click="showZhezhao">接到乘客</span>
        </div>




      </div>
    </van-sticky>





    <!--用户信息栏-->
    <van-sticky :offset-top="750" z-index="50">

      <div class="main-container">
        <div class="sub-box left-container">
          <div>
            <p style="font-size: 20px" class="bold-text">{{userPhone}}</p>
            <p >尾号</p>
          </div>
        </div>
        <div class="sub-box middle">
          <div class="theOrderInderBoxFirst container1">
            <div class="radioBox"></div>
            <div class="" style="width: 150px;margin-left: -50px">{{startaddress}}</div>
          </div>
          <div class="theOrderInderBoxSecond container1">
            <div class="radioBox"></div>
            <div class="" style="width: 150px;margin-left: -50px">{{endaddress}}</div>
          </div>
        </div>
        <div class="sub-box right-container">
          <van-icon  class="icon" name="chat-o" />
          <van-icon class="icon" name="phone" />
        </div>
      </div>
    </van-sticky>
    <div id="showMap"  style="margin-top: -160px;z-index: 1"></div>
    <van-overlay :show="showZheZhaoCeng" z-index="991">
      <div class="container" style="display: flex; flex-direction: column; align-items: center;">
        <div class="input-container">
          <van-field
              v-model="driverUseRandomCode"
              type="digit"
              label="请输入随机码"
              style="height: 80px; line-height: 80px; width: 60%; margin: 0 auto;"
              @click="showKeyBoard = true"
              :maxlength="4"
              @input="onInput"
          />
        </div>
        <div class="button-container">
          <van-button type="primary" @click="submitRandomCode">确定</van-button>
        </div>
      </div>
      <van-number-keyboard
          :show="showKeyBoard"
          @blur="showKeyBoard = false"
          @input="onInput"
          @delete="onDelete"
      />
    </van-overlay>

  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import StartIcon from "@/assets/导航起点.png"
import {
  updateOrderStatus,
  upToUser,
  updateorderTime,
  updateArriveTime,
  UpdateReceiveTime,
  getOrderById, theDriverArrivesAtTheStartingPoint, theDriverPicksUpThePassengers
} from "@/components/api/homepage/homePage";
import {Toast} from "vant";


export default {
  data() {
    return {
      showSpan1:true,
      showKeyBoard:false,
      orderItem:{},
      map: null,
      userPhone: "",
      startaddress:"",
      driverUseRandomCode: "",
      randomCode:"",
      startTranse:[],
      endTranse:[],
      driverTime: null,
      driverLong: null,
      resultAAA:false,
      endaddress:"",
      driverAddress:"",
      // 开始的经纬度
      startLatitudeAndLongitude: "",
      // 结束的经纬度
      endLatitudeAndLongitude: "",
      // 遮罩
      showZheZhaoCeng: false,
    };
  },
  created() {
    if(this.$route.query.orderId){
        this.findOrder();
        this.initAMap();

      //   通过订单id去查找订单信息
    }


  },
  mounted() {

  },
  unmounted() {
    this.map.destroy();
  },


  methods: {
    // 提交验证码
    submitRandomCode(){

      if(this.driverUseRandomCode==this.randomCode){
        updateOrderStatus(this.orderItem.id).then(res=>{
          console.log(res)
        })
        this.$router.push({
          path:"/OnCar",
          query: {
            orderId: this.orderItem.id,
            driverLong:this.driverLong
          }
        })
        this.showZheZhaoCeng=false;
        this.showKeyBoard=false;
        Toast("验证码校验成功!正在为您规划行车路线,请稍候")
      }else {
        Toast('验证码不正确');
      }
    },
    // 验证码输入事件
    onInput(value) {
      // 将新输入的数字附加到现有值上
      // 检查当前输入的数字长度是否小于四位
      if (this.driverUseRandomCode.length < 4) {
        // 将新输入的数字附加到现有值上
        this.driverUseRandomCode += value;
      }
    },

    onDelete() {
      // 删除最后一个字符
      this.driverUseRandomCode = this.driverUseRandomCode.slice(0, -1);
    },

    confirm() {
      alert("确认到达");
    },

    async findOrder(){
      getOrderById(this.$route.query.orderId).then(res=>{
        this.orderItem=res.order;
        // this.startLatitudeAndLongitude=this.orderItem.startingPoint;
        this.endLatitudeAndLongitude=this.orderItem.startingPoint;
        console.log(this.endLatitudeAndLongitude+"终点位置也就是客户的起点")
        this.userPhone=res.order.passengerPhone.substring(7);
        // 随机码
        this.randomCode=res.order.randomCode;

        console.log(this.randomCode+"乘客随机码内容如上")
        // 根据orderid修改司机接单时间
        updateorderTime(res.order.orderId).then(res=>{
          console.log(res)
        })
      })
    },
     initAMap() {
      window._AMapSecurityConfig = {
        securityJsCode: this.$cod,
      };
      let self = this;
      AMapLoader.load({
        key: this.$key, // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Scale","AMap.Geocoder", "AMap.Driving"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
      })
          .then((AMap) => {
                var map = new AMap.Map("showMap", {
                  // 设置地图容器id
                  viewMode: "3D", // 是否为3D地图模式
                  zoom: 11, // 初始化地图级别

                });
                var icon = new AMap.Icon({
                  // 图标尺寸 ===> new AMap.Size(宽, 高)
                  size: new AMap.Size(80, 50),
                  // Icon图片
                  image: StartIcon,
                  // 根据所设置的大小拉伸或压缩图片 ===> new AMap.Size(宽, 高)
                  imageSize: new AMap.Size(50, 50)
                });
                // 逆地址
                var geocoder = new AMap.Geocoder({
                  city: "", //城市设为北京，默认：“全国”
                });
                //添加点标记
                var marker = new AMap.Marker({
                  // position:  [116.397428, 39.90923],
                  // 在这个里面需要设置偏移度,值应和图标的大小一致,如不设置,则会出现定位点随着地图缩略的变化而变化
                  offset: new AMap.Pixel(-50, -50),
                  icon
                });
                map.add(marker); //添加到地图
                AMap.plugin(
                    ["AMap.ToolBar",'AMap.Geolocation', "AMap.Polyline", "AMap.Marker"],
                    function() {
                      //异步同时加载多个插件
                      var toolbar = new AMap.ToolBar();
                      map.addControl(toolbar);

                      // var在函数作用外,否则无法调用

                      // 以下是用于浏览器定位的插件设置
                      var geolocation = new AMap.Geolocation({
                        enableHighAccuracy: true,//是否使用高精度定位，默认:true
                        timeout: 100000,          //超过10秒后停止定位，默认：5s
                        buttonPosition:'RB',    //定位按钮的停靠位置
                        buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                        zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
                      });

                      geolocation.getCurrentPosition(function(status, result) {
                        if (status === 'complete') {
                          var s = JSON.stringify(result.position).slice(1, -1);
                          self.driverAddress = s;
                          console.log(  self.driverAddress + "sdasdasdas");
                          var startTranse = self.driverAddress.split(",");
                          var endTranse = self.orderItem.startingPoint.split(",") ;
                          // var endTranse = self.startLatitudeAndLongitude.split(",");

                          // 在获取到数据后执行后续操作
                          var driving = new AMap.Driving({
                            map: map,
                          }); //驾车路线规划
                          console.log( startTranse + "开始地址")
                          console.log( endTranse + "结束地址")
                          driving.search(
                              new AMap.LngLat(parseFloat(startTranse[0]), parseFloat(startTranse[1])),
                              new AMap.LngLat(parseFloat(endTranse[0]), parseFloat(endTranse[1])),
                              function(status, result) {
                                if (status === "complete") {
                                  console.log("绘制驾车路线完成", result);
                                  self.driverTime = Math.round(result.routes[0].time / 60);
                                  self.driverLong = Math.round(result.routes[0].distance / 1000);

                                  var start = self.orderItem.startingPoint.split(",");
                                  var end = self.orderItem.destination.split(",");
                                  geocoder.getAddress(start, function(status, result) {
                                    if (status === 'complete' && result.regeocode) {
                                      console.log(result + "逆向");
                                      self.startaddress = result.regeocode.formattedAddress;
                                    } else {
                                      console.log("获取开始地址失败");
                                    }
                                  });

                                  geocoder.getAddress(end, function(status, result) {
                                    if (status === 'complete' && result.regeocode) {
                                      self.endaddress = result.regeocode.formattedAddress;
                                    } else {
                                      console.log("获取结束地址失败");
                                    }
                                  });
                                } else {
                                  console.log("获取驾车数据失败：" + result);
                                }
                              }
                          );
                        } else {
                          console.log(result);
                        }
                      });

                    }
                );
              }
          )
    },
    // 展示遮罩层显示用户的验证码
    showZhezhao(){



      //   现在先不写验证码,直接跳转页面

      this.showZheZhaoCeng=true;
      this.showKeyBoard=true;
      UpdateReceiveTime(this.orderItem.orderId).then(res=>{
        console.log(res)
      })
      theDriverPicksUpThePassengers(this.orderItem.orderId).then(res=>{
        console.log(res)
      })



    },
    showSpanMain(){
      this.showSpan1=!this.showSpan1;
      upToUser(this.orderItem.id).then(res=>{
        console.log(res)
      })
      theDriverArrivesAtTheStartingPoint(this.orderItem.id).then(res=>{
        console.log(res)
      })
      /**
       *
       * 司机到达时间
       */
      updateArriveTime(this.orderItem.orderId).then(res=>{
        console.log(res)
      });

    },
  },
};
</script>

<style scoped>
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.block {
  width: 120px;
  height: 120px;
  background-color: #fff;
}
.icon {
  font-size: 50px; /* 设置图标尺寸 */
  display: flex;
  justify-content: center; /* 水平居中对齐 */
  align-items: center; /* 垂直居中对齐 */
  margin-top: 20px;
}

/* 可能需要为 <van-icon> 元素添加额外的样式 */
van-icon {
  width: 100%; /* 确保图标占据整个空间 */
  height: 100%; /* 确保图标占据整个空间 */
}

.radioBox{
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: green ;
  margin-left: -20px;
}
.van-ellipsis111{
  margin-left: -50px;
}
.main-container {

  margin-left: 5%;
  margin-right: 5%;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  background-color: white;
  padding: 10px;
}

.sub-box {
  flex: 1;

}

.sub-box.middle {
  flex: 3;
}

.left-container {
  display: flex;
  justify-content: center; /* 水平居中对齐 */
  align-items: center; /* 垂直居中对齐 */
  flex-direction: column;

}

.right-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.bold-text {
  font-weight: bold;
}
.custom-layout {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: white;
  padding: 10px;
}

.custom-item {
  width: 30%; /* 调整宽度 */
  padding: 5px; /* 调整内边距 */
  height: 30px;
  margin-left: 40px;
  margin-right: 40px;
  border-radius: 20px;
  background-color: lightblue;
}

.custom-item:nth-child(2) {
  background-color: lightgreen;
}

#showMap{
  width: 100%;
  height: 800px;
}
.container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: lightgray;
  padding: 10px;
}
.theOrderInderBoxFirst{
  background-color: white;
}
.theOrderInderBoxSecond{
  background-color: white;
}

.container1 {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left {
  background-color: lightblue;
  padding: 10px;
}

.right {
  padding: 10px;
}
</style>
